
from rest_framework.response import Response
from rest_framework.views import APIView
from django.shortcuts import HttpResponse
from api import models
from api.utils import token
from api.utils.response import BaseResponse


class UserInfoViews(APIView):


    def post(self,request,*args,**kwargs):
        """
        用户登录
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        ret = BaseResponse()
        username = request.data.get('username',None)
        password = request.data.get('password',None)
        remember = request.data.get('remember',None)

        # print(username,password,remember)
        obj = models.UserInfo.objects.filter(username=username,password=password).first()

        if not obj:
            ret.code = -1
            ret.error = '用户名或密码错误'
        else:

            expires_in = 604800

            if remember:
                expires_in = 2592000

            tokenHandler = token.TokenHandler()
            token_key = tokenHandler.produceToken(username)
            token_date,expire_date = tokenHandler.timeStamp(seconds=expires_in)

            models.Token.objects.update_or_create(defaults={
                "token_key":token_key,
                "token_date":token_date,
                "expire_date":expire_date},user=obj)

            ret.data = {
                'access_token': token_key,
                'avatar':'',
                'expires_in':expires_in,
                'has_passwd':True,
                'phone':'',
                'username':username,
            }


        return Response(ret.dict)

